package com.example.finalproject.experiments.camera

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.example.finalproject.R
import java.io.File

class CameraExperimentActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: PhotoAdapter
    private val photoList = mutableListOf<PhotoItem>()
    private val takePhotoLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if (result.resultCode == Activity.RESULT_OK && result.data != null) {
            val photoPath = result.data!!.getStringExtra("photo_path")
            val photoTime = result.data!!.getStringExtra("photo_time")
            if (photoPath != null && photoTime != null) {
                photoList.add(0, PhotoItem(photoPath, photoTime))
                adapter.notifyItemInserted(0)
                recyclerView.scrollToPosition(0)
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera_list)
        recyclerView = findViewById(R.id.recyclerView)
        adapter = PhotoAdapter(photoList)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter
        findViewById<Button>(R.id.btnTakePhoto).setOnClickListener {
            val intent = Intent(this, CameraPreviewActivity::class.java)
            takePhotoLauncher.launch(intent)
        }
    }
}

class PhotoAdapter(private val photos: List<PhotoItem>) : RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotoViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_photo, parent, false)
        return PhotoViewHolder(view)
    }

    override fun onBindViewHolder(holder: PhotoViewHolder, position: Int) {
        val item = photos[position]
        holder.timeView.text = item.time
        holder.imageView.setImageURI(android.net.Uri.fromFile(File(item.path)))
    }

    override fun getItemCount() = photos.size

    class PhotoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val imageView: ImageView = view.findViewById(R.id.imgPhoto)
        val timeView: TextView = view.findViewById(R.id.txtTime)
    }
}